package com.jpa.lgt.util;

import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;

import javax.persistence.EntityManager;
import java.util.List;
import java.util.Map;

/**
 * @author lgt
 * @time 2018/9/18
 * @description：
 */

public class EntityManagerUtil {

    public static List findRelatives(String sql, Map<String, Object> params, EntityManager entityManager, Class<?> clazz) {
        Session session = entityManager.unwrap(Session.class);
        NativeQuery query = session.createNativeQuery(sql);
        query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(clazz));
        for (String key : params.keySet()) {
            Object value = params.get(key);
            query.setParameter(key, value);
        }
        entityManager.close();
        return query.getResultList();

    }
}
